package com.hlkj.interceptor;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.struts2.util.Counter;

import com.hlkj.util.DBPoolUtil;

/**
 * 统计自Web应用被发布后网页被客户端访问的次数，要求当Web应用被终止时，计数器的数值被永久存储在一个文件中或者数据库中，等到Web
 * 应用重新启动时，先从文件或数据库中读取计数器的初始值，然后在此基础上继续计数。
 * 
 * @author zhukui
 * 
 */
public class InitListener implements ServletContextListener {

	@Override
	public void contextDestroyed(ServletContextEvent servletContextEvent) {
		System.out.println("web exit ... ");
		// 获取 ServletContext 对象
		ServletContext context = servletContextEvent.getServletContext();

		// 从 Web 应用范围获得计数器对象
		Counter counter = (Counter) context.getAttribute("counter");
		if (counter != null) {
			try {
				// 把计数器的数值写到 count.txt 文件中
				String filepath = context.getRealPath("/");
				filepath = filepath + "count.txt";
				PrintWriter pw = new PrintWriter(filepath);
				pw.println(counter.getCurrent());
				pw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void contextInitialized(ServletContextEvent servletContextEvent) {
		System.out.println("web init ... ");
		ServletContext context = servletContextEvent.getServletContext();
		try {
			// 从文件中读取计数器的数值
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					context.getResourceAsStream("count.txt")));

			int count = Integer.parseInt(reader.readLine()) + 1;

			reader.close();

			// 创建计数器对象
			Counter counter = new Counter();
			counter.setCurrent(count);

			// 把计数器对象保存到 Web 应用范围
			context.setAttribute("counter", counter);

			// 测试数据库连接
			DBPoolUtil.getConnection();
			System.out.println("---数据库连接成功！！");
		} catch (IOException e) {
			System.out.println("---统计访问量失败！！");
			e.printStackTrace();
		} catch (SQLException e) {
			System.out.println("---数据库连接失败！！");
			e.printStackTrace();
		} finally {
			try {
				DBPoolUtil.close();
			} catch (SQLException e) {
				System.out.println("---数据库断开失败！！");
				e.printStackTrace();
			}
		}
	}

}
